/**
 * <pre>
 *     author : XML
 *     e-mail : 946891360@qq.com
 *     time   : 2019/07/02
 *     version:
 *     desc   :
 * </pre>
 */

import {AsyncStorage} from 'react-native';
import Trending from 'GitHubTrending'

export const FLAG_STORAGE = {flag_popular: 'popular', flag_trending: 'trending'};
export default class DataStore {
    /**
     * 获取数据,优先获取本地数据,如果无本地数据或本地数据过期则获取网络数据
     * @param url
     * @returns {Promise<any> | Promise}
     */
    fetchData(url, flag) {
        return new Promise((resolve, reject) => {
            this.fetchLocalData(url)
                .then(wrapData => {
                    if (wrapData && DataStore.checkTimestampValid(wrapData.timeStamp)) {
                        resolve(wrapData);
                    } else {
                        this.fetchNetData(url, flag)
                            .then(data => this._wrapData(data))
                            .catch(error => reject(error));
                    }
                })
                .catch(error => {
                    error && console.log(error.toString());
                    this.fetchNetData(url, flag)
                        .then(data => this._wrapData(data))
                        .catch(error => reject(error))
                })
        })
    }


    /**
     * 保存数据
     * @param url key
     * @param data value
     * @param callback
     */
    saveData(url, data, callback) {
        if (!data || !url) return;
        AsyncStorage.setItem(url, JSON.stringify(this._wrapData(data)), callback)
    }

    _wrapData(data) {
        return {data: data, timeStamp: new Date().getTime()}
    }

    /**
     * 检查timestamp是否在有效期内
     * @param timestamp
     * @returns {boolean}
     */
    static checkTimestampValid(timestamp) {
        const currentDate = new Date();
        const targetDate = new Date();
        targetDate.setTime(timestamp);
        if (currentDate.getMonth() !== targetDate.getMonth()) return false;
        if (currentDate.getDay() !== targetDate.getDay()) return false;
        if (currentDate.getHours() - targetDate.getHours() > 4) return false;
        // if (currentDate.getMinutes() - targetDate.getMinutes() > 1) return false;
        return true;
    }

    /**
     * 获取本地数据
     * @param url
     * @returns {Promise<any> | Promise}
     */
    fetchLocalData(url) {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(url, (error, result) => {
                if (!error) {
                    try {
                        resolve(JSON.parse(result));
                    } catch (e) {
                        console.log(e);
                    }
                } else {
                    reject(error);
                    console.log(error);
                }
            })
        })
    }

    /**
     * 获取网络数据
     * @param url
     * @param flag
     * @returns {Promise<any> | Promise}
     */
    fetchNetData(url, flag) {
        return new Promise((resolve, reject) => {
            if (flag !== FLAG_STORAGE.flag_trending) {
                fetch(url)
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        }
                        throw new Error('Network response was not ok.');
                    })
                    .then(responseData => {
                        this.saveData(url, responseData);
                        resolve(responseData);
                    })
                    .catch(error => reject(error));
            } else {
                new Trending().fetchTrending(url)
                    .then(items => {
                        if (!items) {
                            throw new Error('responseData is null.');
                        }
                        this.saveData(url, items);
                        resolve(items);
                    })
                    .catch(error => reject(error));
            }

        })
    }
}